//
//  XMLViewController.m
//  NetWork
//
//  Created by cocoazxj@163.com on 15/4/30.
//  Copyright (c) 2015年 handcool. All rights reserved.
//

#import "XMLViewController.h"
#import "VideoModel.h"

@interface XMLViewController ()<NSXMLParserDelegate>
@property (nonatomic, strong) NSMutableArray *mArray;
@end

@implementation XMLViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self XMLAnalyze:@"http://192.168.0.77:8080/MJServer/video?type=XML"];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 使用GDataXML进行解析，基于DOM,用于读取小文件,把XML整个读取,鲸吞。
- (void)analyzeXML:(NSString *)urlString
{
    // 1.将GDataXMLNode.h/m文件添加到工程中
    // 2.向工程中增加“libxml2.dylib”库
    // 3.在工程的“Build Settings”页中找到“Header Search Path”项，添加/usr/include/libxml2"到路径中
    // 4.在Other Linker Flags中加入-lxml2
    // 5.Build phases, compile Source, 引用GDataXMLNode的文件，改成非ARC -fno-objc-arc。
    
}

// 使用NSXMLParser进行解析，基于SAX,用于读取大文件,蚕食。
- (void)XMLAnalyze:(NSString *)urlString
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* connectionError){
        if(data)
        {
            NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
            parser.delegate = self;
            [parser parse];
            for(VideoModel *m in self.mArray)
            {
                NSLog(@"-------%@",m.name);
            }
        }
        
    }];
    
}

// NSXMLParser需要实现的代理方法
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    NSLog(@"----------parserDidStartDocument----");
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"----------parserDidEndDocument----");
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"videos"])
    {
        self.mArray = [NSMutableArray array];
    }
    else if([elementName isEqualToString:@"video"])
    {
        VideoModel *m = [VideoModel videoWithDict:attributeDict];
        [self.mArray addObject:m];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"----------%lu----",(unsigned long)self.mArray.count);
}
@end
